package com.zzh.takeoutapp.activity;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.UiSettings;
import com.baidu.mapapi.model.LatLng;
import com.yinglan.scrolllayout.ScrollLayout;
import com.zzh.takeoutapp.R;
import com.zzh.takeoutapp.adapter.OrderDetailsAdapter;
import com.zzh.takeoutapp.base.BaseActivity;
import com.zzh.takeoutapp.entity.OrderDetailsBean;
import com.zzh.takeoutapp.event.NetMsgEvent;
import com.zzh.takeoutapp.map.LocationService;
import com.zzh.takeoutapp.service.EventbusHelper;
import com.zzh.takeoutapp.service.ServiceUrl;
import com.zzh.takeoutapp.utils.DividerGridItemDecoration;
import com.zzh.takeoutapp.utils.GsonResolve;
import com.zzh.takeoutapp.utils.ImageManager;
import com.zzh.takeoutapp.utils.LoadingUtil;
import com.zzh.takeoutapp.utils.ToolBarHelper;
import com.zzh.takeoutapp.utils.UtilTool;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2018/7/31.
 */

public class OrderDetailsActivity extends BaseActivity {

    @Bind(R.id.tv_pay)
    TextView tv_pay;
    @Bind(R.id.tv_see)
    TextView tv_see;
    @Bind(R.id.tv_admin)
    TextView tv_admin;
    @Bind(R.id.tv_confirm)
    TextView tv_confirm;
    @Bind(R.id.tv_cui)
    TextView tv_cui;
    @Bind(R.id.tv_cancel_refund)
    TextView tv_cancel_refund;//取消退款
    @Bind(R.id.tv_apply_refund)
    TextView tv_apply_refund;//申请退款
    @Bind(R.id.tv_evaluate_refund)
    TextView tv_evaluate_refund;//马上评价
    @Bind(R.id.tv_recur_refund)
    TextView tv_recur_refund;//再来一单
    @Bind(R.id.tv_equal_refund)
    TextView tv_equal_refund;//相似商家
    @Bind(R.id.tv_money)
    TextView tv_money;//总计
    @Bind(R.id.tv_addr)
    TextView tv_addr;
    @Bind(R.id.tv_order_num)
    TextView tv_order_num;
    @Bind(R.id.tv_copy)
    TextView tv_copy;
    @Bind(R.id.tv_package_price)
    TextView tv_package_price;
    @Bind(R.id.tv_hongbao_num)
    TextView tv_hongbao_num;
    @Bind(R.id.tv_freight)
    TextView tv_freight;
    @Bind(R.id.iv_logo)
    ImageView iv_logo;
    @Bind(R.id.tv_title)
    TextView tv_title;
    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    @Bind(R.id.toolbar)
    Toolbar tbToolbar;
    @Bind(R.id.view_pager)
    LinearLayout view_pager;
    @Bind(R.id.scroll_down_layout)
    ScrollLayout mScrollLayout;
    @Bind(R.id.shop_phone)
    LinearLayout shop_phone;//商家电话
    private MapView mMapView;
    private BaiduMap mBaiduMap;
    private MyLocationListener mListener = new MyLocationListener();
    private boolean isFirstLoc = true;
    private LocationService locationService;
    private Marker mMarkerA;
    private InfoWindow mInfoWindow;
    private UiSettings mUiSettings;
    private final String ORDER_DETAILS = "OrderDetailsActivity";
    private BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory.fromResource(R.drawable.icon_markf);
    private LoadingUtil loadingUtil;
    private OrderDetailsAdapter shopAdapter;
    private List<OrderDetailsBean.DataBean.DetailBean.ProductsBean> beans;
    private String mPhone;//商家电话

    @Override
    public void setContent() {
        setContentView(R.layout.activity_home_order_details);
        ButterKnife.bind(this);
        loadingUtil = new LoadingUtil(this);
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void initComponent() {
        loadingUtil.startShowLoading();
        mMapView = (MapView) findViewById(R.id.map_View);
        mBaiduMap = mMapView.getMap();
        mBaiduMap.setMyLocationEnabled(true);
        mUiSettings = mBaiduMap.getUiSettings();
        mUiSettings.setCompassEnabled(false);//是否启用指南针图层
        mBaiduMap.showMapPoi(true);//是否显示底图默认标注
        mUiSettings.setScrollGesturesEnabled(true);//是否启用平移手势
        mUiSettings.setZoomGesturesEnabled(true);  //是否启用缩放手势
        mUiSettings.setRotateGesturesEnabled(false);//是否启用旋转手势
        mUiSettings.setOverlookingGesturesEnabled(false);//是否启用俯视手势
        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                return true;
            }
        });

        ServiceUrl.OrderDetailService(this, getIntent().getStringExtra("order_id"),
                ORDER_DETAILS);
        ToolBarHelper.setTitleAndBackAndText(this, tbToolbar, "我的订单");
    }

    @Override
    public void setListener() {
        beans = new ArrayList<>();
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.addItemDecoration(new DividerGridItemDecoration(this, 1, R.color.font_black_6));
        view_pager.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mScrollLayout.getCurrentStatus() == ScrollLayout.Status.OPENED) {
                    mScrollLayout.scrollToClose();
                } else {
                    UtilTool.toast(OrderDetailsActivity.this, "wode");
                }
            }
        });

    }

    @Override
    public void onAfterInit() {
    }


    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            if (bdLocation == null || mMapView == null) {
                return;
            }
            MyLocationData locData = new MyLocationData.Builder().accuracy(bdLocation.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(bdLocation.getDirection()).latitude(bdLocation.getLatitude())
                    .longitude(bdLocation.getLongitude()).build();
            // 设置定位数据
            mBaiduMap.setMyLocationData(locData);
            //地图SDK处理
            if (isFirstLoc) {
                isFirstLoc = false;
                LatLng ll = new LatLng(bdLocation.getLatitude(),
                        bdLocation.getLongitude());
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(ll).zoom(18.0f);
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
            }
            LatLng point = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());
            MarkerOptions ooA = new MarkerOptions().position(point).icon(mCurrentMarker)
                    .zIndex(9).draggable(true);
            // 掉下动画
            // ooA.animateType(MarkerOptions.MarkerAnimateType.drop);
            mMarkerA = (Marker) (mBaiduMap.addOverlay(ooA));
            Button button = new Button(getApplicationContext());
            button.setBackgroundResource(R.mipmap.popup);
            InfoWindow.OnInfoWindowClickListener listener = new InfoWindow.OnInfoWindowClickListener() {
                @Override
                public void onInfoWindowClick() {
                    // mBaiduMap.hideInfoWindow();
                }
            };
            mInfoWindow = new InfoWindow(BitmapDescriptorFactory.fromView(button), point, -147, listener);
            mBaiduMap.showInfoWindow(mInfoWindow);

            locationService.stop(); //停止定位服务


        }
    }


    @Override
    public void onStop() {
        locationService.unregisterListener(mListener); //注销掉监听
        locationService.stop(); //停止定位服务
        EventbusHelper.unregister(this);
        super.onStop();
    }

    private ScrollLayout.OnScrollChangedListener mOnScrollChangedListener =
            new ScrollLayout.OnScrollChangedListener() {
                @Override
                public void onScrollProgressChanged(float currentProgress) {
                    if (currentProgress >= 0) {
                        float precent = 255 * currentProgress;
                        if (precent > 255) {
                            precent = 255;
                        } else if (precent < 0) {
                            precent = 0;
                        }
                        mScrollLayout.getBackground().setAlpha(255 - (int) precent);
                        mMapView.getBackground().setAlpha(255 - (int) precent);
                    }
                }

                @Override
                public void onScrollFinished(ScrollLayout.Status currentStatus) {
                    if (currentStatus.equals(ScrollLayout.Status.EXIT)) {
                        finish();
                    }
                }

                @Override
                public void onChildScroll(int top) {
                }
            };

    @Override
    public void onStart() {
        super.onStart();
        EventbusHelper.register(this);
        locationService = new LocationService(this);
        locationService.registerListener(mListener);
        locationService.setLocationOption(locationService.getDefaultLocationClientOption());
        locationService.start();// 定位SDK
    }

    @OnClick({R.id.shop_phone, R.id.tv_copy})
    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.shop_phone:
                Intent ll_clientele = new Intent(Intent.ACTION_DIAL);
                ll_clientele.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                ll_clientele.setData(Uri.parse("tel:" + mPhone.trim()));
                start_Activity(ll_clientele);
                break;
            case R.id.tv_copy:
                //获取剪贴板管理器：
                ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                // 创建普通字符型ClipData
                ClipData mClipData = ClipData.newPlainText("Label", tv_order_num.getText().toString());
                // 将ClipData内容放到系统剪贴板里。
                cm.setPrimaryClip(mClipData);
                UtilTool.toast(this, "复制完成");
                break;

        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        // activity 暂停时同时暂停地图控件
        if (mMapView != null)
            mMapView.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        // activity 恢复时同时恢复地图控件
        if (mMapView != null)
            mMapView.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // activity 销毁时同时销毁地图控件
        MapView.setMapCustomEnable(false);
        mMapView.onDestroy();
        mMapView = null;
        mCurrentMarker.recycle();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMsgEvent(NetMsgEvent event) {
        String _msgType = (String) event.getMsgType();
        JSONObject jsonObject = event.getMsgJSONObj();
        switch (_msgType) {
            case ORDER_DETAILS:
                loadingUtil.stopShowLoading();
                if (jsonObject != null)
                    if (jsonObject.optString("message").equals("success")) {
                        OrderDetailsBean orderDetailsBean = GsonResolve.jsonString2Bean(jsonObject.toString(), OrderDetailsBean.class);
                        initView(orderDetailsBean);
                    }
                break;
        }
    }

    private void initView(OrderDetailsBean orderDetailsBean) {
        OrderDetailsBean.DataBean.DetailBean.WaimaiBean waimaiBean = orderDetailsBean.getData().getDetail().getWaimai();

        Log.e("---waimaiBean---",orderDetailsBean.getData().getDetail().getOrder_status());
        if (Integer.parseInt(orderDetailsBean.getData().getDetail().getOrder_status()) < 8) {
            mMapView.setVisibility(View.GONE);
            mScrollLayout.getBackground().setAlpha(255);
            mScrollLayout.setToClosed();
            mScrollLayout.setEnable(false);
            mScrollLayout.setOnScrollChangedListener(null);
            mScrollLayout.setBackgroundColor(getResources().getColor(R.color.white));
        } else {
            mScrollLayout.setToOpen();
            mScrollLayout.setOnScrollChangedListener(mOnScrollChangedListener);
        }
        ImageManager.loadUrlImage(this, waimaiBean.getLogo(), iv_logo);
        tv_money.setText("合计:￥" + orderDetailsBean.getData().getDetail().getTotal_price());
        tv_title.setText(waimaiBean.getTitle());
        tv_package_price.setText("￥" + orderDetailsBean.getData().getDetail().getPackage_price());
        tv_freight.setText("￥" + orderDetailsBean.getData().getDetail().getFreight());
        tv_hongbao_num.setText("-￥" + orderDetailsBean.getData().getDetail().getHongbao_num());
        tv_freight.setText("￥" + orderDetailsBean.getData().getDetail().getFreight());
        tv_addr.setText(orderDetailsBean.getData().getDetail().getContact() + "    " +
                orderDetailsBean.getData().getDetail().getMobile() + "\n" +
                orderDetailsBean.getData().getDetail().getAddr() + "    " +
                orderDetailsBean.getData().getDetail().getHouse());
        setView(orderDetailsBean.getData().getDetail().getShow_btn());
        mPhone = waimaiBean.getPhone();
        beans.addAll(orderDetailsBean.getData().getDetail().getProducts());
        shopAdapter = new OrderDetailsAdapter(beans, this);
        recyclerView.setAdapter(shopAdapter);
        shopAdapter.notifyDataSetChanged();
    }

    private void setView(OrderDetailsBean.DataBean.DetailBean.ShowBtnBean show_btn) {
        if (show_btn.getCanel().equals("1")) {
            tv_cancel_refund.setVisibility(View.VISIBLE);
        } else {
            tv_cancel_refund.setVisibility(View.GONE);
        }
        if (show_btn.getComment().equals("1")) {
            tv_evaluate_refund.setVisibility(View.VISIBLE);
        } else {
            tv_evaluate_refund.setVisibility(View.GONE);
        }
        if (show_btn.getPayback().equals("1")) {
            tv_apply_refund.setVisibility(View.VISIBLE);
        } else {
            tv_apply_refund.setVisibility(View.GONE);
        }
        if (show_btn.getAgain().equals("1")) {
            tv_recur_refund.setVisibility(View.VISIBLE);
        } else {
            tv_recur_refund.setVisibility(View.GONE);
        }
        if (show_btn.getSee().equals("1")) {
            tv_equal_refund.setVisibility(View.VISIBLE);
        } else {
            tv_equal_refund.setVisibility(View.GONE);
        }
        if (show_btn.getPay().equals("1")) {
            tv_pay.setVisibility(View.VISIBLE);
        } else {
            tv_pay.setVisibility(View.GONE);
        }
        if (show_btn.getSee().equals("1")) {
            tv_see.setVisibility(View.VISIBLE);
        } else {
            tv_see.setVisibility(View.GONE);
        }
        if (show_btn.getAdmin().equals("1")) {
            tv_admin.setVisibility(View.VISIBLE);
        } else {
            tv_admin.setVisibility(View.GONE);
        }
        if (show_btn.getConfirm().equals("1")) {
            tv_confirm.setVisibility(View.VISIBLE);
        } else {
            tv_confirm.setVisibility(View.GONE);
        }
        if (show_btn.getCui().equals("1")) {
            tv_cui.setVisibility(View.VISIBLE);
        } else {
            tv_cui.setVisibility(View.GONE);
        }


    }
}
